const { defineConfig } = require('@vue/cli-service')
const mock = require('mockjs')
const bodyParser = require('body-parser') // 转json中间件
const { list } = mock.mock({
  "list|40": [
    {
      "id": "@id",
      "image": "@image(200x200,@color)",
      "title": "@ctitle(30,50)",
      "price|1-100": 1
    }
  ]
})
const users = []

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    // 定义接口地址
    setupMiddlewares: (mid, { app }) => {
      app.use(bodyParser.json())
      // app.get('/api/list', (req, res) => {
      //   res.send({
      //     code: 200,
      //     data: list
      //   })
      // })
      app.get('/api/list', (req, res) => {
        const { pagination, pageNum } = req.query;
        res.send({
          code: 200,
          // 第一次pagination1: 0 1 2 3 4 5 6 7 8 9 
          // 第二次pagination2: 10 11 12 13 14 15 16 17 18 19 20
          data: list.slice((pagination - 1) * pageNum, pagination * pageNum),
          total: list.length
        })
      })
      // 定义获取详情接口
      app.get('/api/getItem', (req, res) => {
        const { id } = req.query;
        // 数组的操作方式.find
        const item = list.find(item => item.id === id);
        res.send({
          code: 200,
          data: item
        })
      })
      app.post('/api/register', (req, res) => {
        console.log(req.body, 'body')
        const { username, password } = req.body;
        // // every/some
        const isAdd = users.every(item => item.username !== username)
        if (isAdd) {
          users.push({ // 在数组的最后添加一条
            username,
            password
          })
          res.send({
            code: 200,
            message: '注册成功'
          })
        } else {
          res.send({
            code: 0,
            message: '当前账号已经被注册了～'
          })
        }
      })
      app.post('/api/login', (req, res) => {
        console.log(req.body, 'body')
        const { username, password } = req.body;
        const user = users.find(item => item.username === username && item.password === password)
        if (user) {
          res.send({
            code: 200,
            token: 'yijingdengluchenggong'
          })
        } else {
          res.send({
            code: 0,
            message: '用户名不存在或密码错误'
          })
        }
      }),
        app.get('/api/query', (req, res) => {
          const { value } = req.query;
          res.send({
            code: 200,
            list: list.filter(item => item.title.includes(value))
          })
        })
      return mid
    }


  }
})
